package com.zadtek.shopmall.net;

import android.support.v4.util.ArrayMap;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.bean.UpLoadImgResponse;
import com.zadtek.shopmall.other.Const;
import com.zadtek.shopmall.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Zackv on 2018/3/16.
 */

public class NetTool {
//    public static final String BaseUrl = "http://5adef0b3bf932f0014d11b3a.mockapi.io/";
//    public static final String BaseUrl = "http://xmlife.zadtek.com/";

    private Api mAPI;
    private static NetTool netTool = null;

    private NetTool() {
        //mHeader.put("Accept", "application/json, version=100");
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.addInterceptor(new LogInterceptor());
        httpClient.retryOnConnectionFailure(true);
        mAPI = new Retrofit.Builder()
                .client(httpClient.build())
                .baseUrl(Const.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
                .create(Api.class);
    }

    private static NetTool getHelper() {
        if (netTool == null) {
            synchronized (NetTool.class) {
                if (netTool == null) {
                    netTool = new NetTool();
                }
            }
        }
        return netTool;
    }

    public static Api getApi() {
        return getHelper().mAPI;
    }

    public static Map<String, Object> newParams() {
        final Map<String, Object> params = new ArrayMap<String, Object>();
        params.put("uid", Const.userid);
        params.put("token", Const.token);
        return params;
    }

    public static RequestBody buildUploadMultipart(File file, String key) {
        return new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
    }

    public static Observable<BaseResponse<UpLoadImgResponse>> uploadFile(String path){
        RequestBody body = buildUploadMultipart(new File(path),"image");
        return getApi().uploadImg(body);
    }

    public static Observable<BaseResponse<OperateResponseBean3>> uploadAvatar(String path){
        File file = new File(path);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("uid", String.valueOf(Const.userid));
        builder.addFormDataPart("token", String.valueOf(Const.token));
        builder.addFormDataPart("image",file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),file));
        RequestBody body = builder.build();
        return getApi().updateUserAvatar(body);
    }

    public static Observable<BaseResponse<UpLoadImgResponse>> uploadFile(List<String> paths){
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("imgNum", String.valueOf(paths.size()));
        for(int i = 0;i<paths.size();i++){
            File file = new File(paths.get(i));
            builder.addFormDataPart("img"+i,file.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),file));
        }
        RequestBody body = builder.build();
        return getApi().uploadImg(body);
    }

    private static class LogInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder().addHeader("Connection","close").build();;
            LogUtil.d2(request);
            if (request.body() instanceof FormBody) {
                FormBody form = (FormBody) request.body();
                for (int index = 0, size = form.size(); index < size; index++) {
                    LogUtil.d2(form.encodedName(index), form.encodedValue(index));
                }
            }
            Response response = chain.proceed(request);
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            LogUtil.d(content);
            return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
        }
    }
}
